<template>
    <div>
        <el-form :model="contractForm" ref="contractForm"  label-width="100px"  >
            <div style="width:460px">
            <el-form-item label="签订市场：" prop="marketId">
				<el-select v-model="contractForm.marketId" placeholder="请选择市场">
					<el-option v-for="(item,index) in store.marketOptions" :key="item.marketId" :label="item.marketName" :value="item.marketId"></el-option>
				</el-select>
			</el-form-item>
             <el-form-item label="签订商户：" prop="shopId">
				<el-select v-model="contractForm.shopId" placeholder="请选择商户">
					<el-option v-for="(item,index) in store.shopOptions" :key="item.shopId" :label="item.shopName" :value="item.shopId"></el-option>
				</el-select>
			</el-form-item>
            <el-form-item label="合同编号：" prop="contractNo">
                 <el-input v-model="contractForm.contractNo" placeholder="请输入合同编号" clearable></el-input>
			</el-form-item>
            <el-form-item label="合同状态：" prop="contractState">
                <el-radio-group  v-model="contractForm.contractState">
                    <el-radio :label="1">有效</el-radio>
                    <el-radio :label="0">无效</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item  label="起始时间："  prop="contractStartDate">
                <el-date-picker type="date" v-model="contractForm.contractStartDate" name="contractStartDate" placeholder="选择日期"  value-format="yyyy-MM-dd">
				</el-date-picker>
            </el-form-item>
             <el-form-item label="截止时间：" prop="contractEndingDate">
                <el-date-picker type="date" v-model="contractForm.contractEndingDate" name="contractEndingDate" placeholder="选择日期" value-format="yyyy-MM-dd">
				</el-date-picker>
            </el-form-item>
            </div>
            <el-button  type="primary" @click="addContractRegionInfo()" style="margin-bottom: 20px" :disabled="canAdd">新增合同明细</el-button>
            <el-table  :data="contractRegionList" border>
                <el-table-column prop="regionName" label="区域名称" ></el-table-column>
                <el-table-column prop="contractRegionRentFee" label="月租金(元)" ></el-table-column>
                <el-table-column prop="contractRegionRentCount" label="租赁面积/车位" ></el-table-column>
                <el-table-column prop="contractRegionAmount" label="月租赁总金额(元)" ></el-table-column>
                <el-table-column prop="contractRegionCarNo" label="场地号" ></el-table-column>
                <el-table-column prop="contractRegionParkCount" label="车位数(个)" ></el-table-column>
                <el-table-column label="状态" align="center" width="200">
                    <template slot-scope="scope">
                        <span>{{scope.row.contractRegionState | filteContractState}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="200">
                    <template slot-scope="scope">
                        <el-button @click="handleDelete(scope.$index)"  size="small"  type="primary">移除</el-button>
                        <el-button @click="handleEdit(scope.$index)"  size="small"  type="primary">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <addContractRegion :params="addContractInfo" :params2="params2" @insert="insertContractRegionList" />
               <div class="dialog-footer" style="margin-top: 20px">
                <el-button type="primary" @click="onSubmit()">{{buttonName}}</el-button>
                <el-button @click="turnToList">返回列表</el-button>
            </div>
        </el-form>
    </div>
</template>
<script>
  import addContractRegion from './addContractRegion.vue'
export default {
    data() {
        return {
          num:0,
          buttonName:'',
          contractId: this.$route.params.id,
          contractRegionList: [],
          canAdd: true,
          contractForm:{
             marketId: null,
             shopId: null,
             contractState: 1,
             contractNo: '',
             contractStartDate: '',
             contractEndingDate: ''
          },
          store:{
            marketOptions:[],
            shopOptions:[],
            params:{
                pageSize:10,
                pageIndex:1,
                marketId:this.$marketId,
                shopId: null
            },
         },
        addContractInfo: {
            addInfo:false,
            marketId: this.$marketId,
            contractRegionList: []
        },
        params2:{
            edit: false,
        },
     };
    },
     watch:{
        '$route'(){
            if (!this.$route.params.id){
                this.resetForm('contractForm')
                this.buttonName = '立即创建'
            }
        },
        'contractForm.marketId'(){
            if (this.contractForm.marketId){
                this.canAdd = false
                this.store.params.marketId = this.contractForm.marketId
                this.$store.commit('getShopOptions',this.store)
            }else{
                this.canAdd = true
            }
        },
        'contractForm.contractNo'(){
            this.$axios.get(this.$api.getContractNum,{params: {contractNo: this.contractForm.contractNo, marketId: this.contractForm.marketId}})
    		.then((res)=>{
                if (res.data.result > 0){
                    this.$message({
                        message: '合同编号已经存在',
                        type: 'success'
                    });
                   this.contractForm.contractNo = ''
                }
    		})
        }
    },
    created(){
       this.$store.commit('getMarketOptions',this.store)

    },
    components:{
        addContractRegion
    },
    methods: {
        insertContractRegionList(obj){
            this.contractRegionList.push(JSON.parse(obj))
        },
        filterForMat(value){
            Date.prototype.toLocaleString = function() {
                return this.getFullYear() + "-" + ((this.getMonth()+1 >= 1 && this.getMonth()+1 <= 9) ? "0" + (this.getMonth()+1):this.getMonth()+1) + "-" +((this.getDate() >= 1 && this.getDate() <= 9) ? "0" + this.getDate():this.getDate())
            };
            var unixTimestamp = new Date(value) ;
            return unixTimestamp.toLocaleString();
        },
        turnToList(){
            this.$router.push('/contract/contractList')
        },
        addContractRegionInfo(){
            this.params2.edit = false
            this.addContractInfo.addInfo = true
            this.addContractInfo.marketId = this.contractForm.marketId
            this.addContractInfo.contractRegionList = this.contractRegionList
        },
        handleDelete(index){
            this.$confirm('此操作将删除数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {
                   this.contractRegionList.splice(index,1);
                });
        },

        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        handleEdit(index){
            this.addContractInfo.addInfo = true
            this.params2 = this.contractRegionList[index]
            this.params2.edit = true
        },
        onSubmit() {
            var requestParam = this.contractForm
			requestParam.contractRegionList =  JSON.stringify(this.contractRegionList);
            var formData = new FormData();
            for(let i in requestParam){
               formData.append(i,requestParam[i])
            }
          	this.$axios({
                method: 'post',
                url: this.$api.insertContract,
                data: formData
                }).then((res) => {
                if (res.data.code == 1){
                    this.$message({
                        message: res.data.msg,
                        type: 'success'
                    });
                    this.$router.push('/contract/contractList')
                }else{
                    this.$message({
                        message: res.data.msg,
                        type: 'error'
                    });
                    this.$router.push('/contract/contractForm')
                }
        })

        },

    },
    activated() {
        this.contractRegionList = []
       this.buttonName = "立即创建"
    },
    deactivated() {

    }
}
</script>
